<template>
  <div>
    <el-select v-model="cValue" @change="onChange" :multiple="multiple" v-bind="$attrs">
      <el-option
        v-for="item in options"
        :key="item[fieldNames.value]"
        :label="item[fieldNames.label]"
        :value="item[fieldNames.value]"
      />
    </el-select>
  </div>
</template>

<script setup lang="js">
import { ref, watch, defineProps, defineEmits } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Array],
    required: false,
  },
  fieldNames: {
    type: Object,
    default: () => {
      return {
        label: 'label',
        value: 'value',
      }
    },
  },
  options: {
    type: Array,
    default: () => [],
    required: false,
  },
  isStringValue: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue', 'change'])

const cValue = ref(initializeValue(props.modelValue))

watch(
  () => props.modelValue,
  newVal => {
    cValue.value = initializeValue(newVal)
  }
)

function initializeValue(val) {
  if (props.multiple) {
    if (Array.isArray(val)) {
      return val
    }
    if (typeof  val === 'string' && val) {
      return val.split(',')
    }
    return []
  }
  return Array.isArray(val) ? (val.length > 0 ? val[0] : '') : val
}
function onChange(v) {
  cValue.value = v
  const returnValue = props.isStringValue
    ? Array.isArray(cValue.value)
      ? cValue.value.join(',')
      : cValue.value
    : cValue.value
  emit('update:modelValue', returnValue)

  emit('change', returnValue)
}
</script>
